// 全局JavaScript功能

// DOM加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 登录表单提交
    const loginForm = document.getElementById('loginForm');
    if (loginForm) {
        loginForm.addEventListener('submit', function(e) {
            e.preventDefault();
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;

            // 这里应该有实际的验证逻辑
            console.log('登录尝试:', username, password);

            // 模拟登录成功跳转
            window.location.href = 'index.html';
        });
    }

    // 退出登录
    const logoutButtons = document.querySelectorAll('.logout');
    logoutButtons.forEach(button => {
        button.addEventListener('click', function(e) {
            e.preventDefault();
            // 这里应该有实际的退出逻辑
            console.log('用户退出');
            window.location.href = 'login.html';
        });
    });

    // 数据表格排序功能
    const tables = document.querySelectorAll('.data-table');
    tables.forEach(table => {
        const headers = table.querySelectorAll('th');
        headers.forEach((header, index) => {
            if (header.textContent.trim() && !header.querySelector('input') && !header.querySelector('button')) {
                header.style.cursor = 'pointer';
                header.addEventListener('click', () => {
                    sortTable(table, index);
                });
            }
        });
    });

    // 表单验证示例
    const forms = document.querySelectorAll('form');
    forms.forEach(form => {
        form.addEventListener('submit', function(e) {
            let isValid = true;
            const inputs = form.querySelectorAll('input[required], select[required], textarea[required]');

            inputs.forEach(input => {
                if (!input.value.trim()) {
                    input.style.borderColor = '#e74c3c';
                    isValid = false;
                } else {
                    input.style.borderColor = '#ddd';
                }
            });

            if (!isValid) {
                e.preventDefault();
                alert('请填写所有必填字段');
            }
        });
    });

    // 动态添加入库商品行示例
    const addProductBtn = document.querySelector('.table-actions .btn-sm');
    if (addProductBtn) {
        addProductBtn.addEventListener('click', function() {
            const tbody = document.querySelector('.data-table tbody');
            const emptyRow = tbody.querySelector('.empty-row');

            if (emptyRow) {
                tbody.removeChild(emptyRow);
            }

            const newRow = document.createElement('tr');
            newRow.innerHTML = `
                <td><input type="text" placeholder="输入商品编码"></td>
                <td><input type="text" placeholder="输入商品名称"></td>
                <td><input type="text" placeholder="输入规格型号"></td>
                <td><input type="text" placeholder="单位"></td>
                <td><input type="number" placeholder="数量"></td>
                <td><input type="text" placeholder="批次号"></td>
                <td><input type="date"></td>
                <td><input type="text" placeholder="库位"></td>
                <td><button class="btn-sm remove-row">删除</button></td>
            `;

            tbody.appendChild(newRow);

            // 为新添加的删除按钮添加事件
            newRow.querySelector('.remove-row').addEventListener('click', function() {
                tbody.removeChild(newRow);
                if (tbody.children.length === 0) {
                    const emptyRow = document.createElement('tr');
                    emptyRow.className = 'empty-row';
                    emptyRow.innerHTML = '<td colspan="9">暂无商品，请添加</td>';
                    tbody.appendChild(emptyRow);
                }
            });
        });
    }
});

// 表格排序函数
function sortTable(table, column) {
    const tbody = table.querySelector('tbody');
    const rows = Array.from(tbody.querySelectorAll('tr'));
    const isNumeric = !isNaN(parseFloat(rows[0].cells[column].textContent));

    rows.sort((a, b) => {
        const aValue = a.cells[column].textContent.trim();
        const bValue = b.cells[column].textContent.trim();

        if (isNumeric) {
            return parseFloat(aValue) - parseFloat(bValue);
        } else {
            return aValue.localeCompare(bValue);
        }
    });

    // 清除现有行
    while (tbody.firstChild) {
        tbody.removeChild(tbody.firstChild);
    }

    // 添加排序后的行
    rows.forEach(row => {
        tbody.appendChild(row);
    });
}

// 模拟数据加载
function loadData() {
    // 这里应该有实际的API调用
    console.log('加载数据...');

    // 模拟API延迟
    return new Promise(resolve => {
        setTimeout(() => {
            resolve({ success: true });
        }, 1000);
    });
}

// 导出功能
function exportToExcel() {
    // 这里应该有实际的导出逻辑
    console.log('导出数据到Excel');
}

// 全局工具函数
function formatDate(date) {
    if (!date) return '';
    const d = new Date(date);
    return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`;
}